package chen.web.util.jdbc.wrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import chen.web.MyContext;
import chen.web.MyContextProvider;

public class QueryInfoHandler implements EventHandler {
	
	private String contextAttributeName = null;
	
	private static Log log = LogFactory.getLog(QueryInfoHandler.class);
	
	public QueryInfoHandler(String contextAttributeName){
		if(contextAttributeName == null || contextAttributeName.length() == 0){
			throw new IllegalArgumentException();
		}
		this.contextAttributeName = contextAttributeName;
	}
	
	private void afterExecute() {
		// TODO Auto-generated method stub
		MyContext context = MyContextProvider.getMyContext();
		if(context != null){
			QueryInfo info = (QueryInfo)context.getAttribute(contextAttributeName);
			if(info != null){
				long queryTime  = System.nanoTime() - info.getStartTime();
				
				info.setQueryCount(info.getQueryCount() + 1);
				info.setQueryTime(info.getQueryTime() + queryTime);	
			} else {
				if(log.isDebugEnabled()){
					log.debug("在上下文中找不到属性名:" + contextAttributeName + ", 不能记录jdbc查询信息");
				}
			}	
		} else {
			if(log.isDebugEnabled()){
				log.debug("没有设置上下文, 不能记录jdbc查询信息");
			}
		}	
	}

	private void beforeExecute() {
		// TODO Auto-generated method stub
		MyContext context = MyContextProvider.getMyContext();
		if(context != null){
			QueryInfo info = (QueryInfo)context.getAttribute(contextAttributeName);
			if(info != null){
				info.setStartTime(System.nanoTime());	
			}else {
				if(log.isDebugEnabled()){
					log.debug("在上下文中找不到属性名:" + contextAttributeName + ", 不能记录jdbc查询信息");
				}
			}	
		}else {
			if(log.isDebugEnabled()){
				log.debug("没有设置上下文, 不能记录jdbc查询信息");
			}
		}	
	}

	@Override
	public void handler(Event event) {
		// TODO Auto-generated method stub
		switch(event){
		case BeforeExecute : {
			beforeExecute();
			break;
		}
		case AfterExecute :	 {
			afterExecute();
			break;
		}
		}
	}

}
